<!-- eslint-disable vue/no-mutating-props -->
<template>
  <el-form :model="model" :rules="rules" ref="formRef">
    <el-form-item
      v-for="(formItem, index) in schema"
      :key="index"
      :label="formItem.label"
      :prop="formItem.prop"
    >
      <el-input
        v-if="formItem.type === 'input'"
        v-bind="formItem.props"
        v-model="model[formItem.prop]"
      ></el-input>
      <el-select
        v-else-if="formItem.type === 'select'"
        v-bind="formItem.props"
        v-model="model[formItem.prop]"
      >
        <el-option
          v-for="option in formItem.selectOptions"
          :key="option.id"
          :label="option.label"
          :value="option.value"
        ></el-option>
      </el-select>
      <el-upload
        v-else-if="formItem.type === 'upload'"
        v-bind="formItem.props"
        v-model:file-list="model[formItem.prop]"
      >
        <el-button type="primary">上传</el-button>
        <template #tip v-if="formItem.tip">
          <div class="el-upload__tip">
            {{ formItem.tip }}
          </div>
        </template>
      </el-upload>
      <!-- 使用具名插槽 -->
      <slot v-else-if="formItem.type === 'slot'" :name="formItem.slot" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts">
export default {
  name: "XForm",
};
</script>

<script lang="ts" setup>
import { ref } from "vue";
import type { FormRules } from "element-plus";

interface Model {
  [key: string]: any;
}

defineProps<{
  schema: any;
  model: Model;
  rules: FormRules;
}>();

const emit = defineEmits(["submit"]);

const formRef = ref();

const submit = async () => {
  // 校验表单方法
  await formRef.value.validate();

  emit("submit");
};
</script>

<style scoped></style>
